package com.watercube.note.biz.user.aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.watercube.common.annotation.LogRTtimeLimit;
import com.watercube.common.constant.ConstantField.LogRTtimeLimitConstant;

import lombok.extern.slf4j.Slf4j;

/**
 * @Project: water-cube-note-user
 * @Description 记录RT超出范围的aop
 * @author yangyh
 * @date 2018年1月17日
 * @version V1.0
 */
@Aspect
@Slf4j
@Component
public class BizLogRTAop {

	private long startTimeMillis = 0; // 开始时间
	private long endTimeMillis = 0; // 结束时间

	@Pointcut("execution(* com.watercube.note.biz.user.impl.*.*(..))")
	public void pointcut() {
	}

	@Before("pointcut()")
	public Object beforePointcut(JoinPoint pjp) throws Throwable {
		startTimeMillis = System.currentTimeMillis(); // 记录方法开始执行的时间
		return pjp;
	}

	@After("pointcut()")
	public Object afterPointcut(JoinPoint pjp) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();

		long limitTime = LogRTtimeLimitConstant.BIZ_DEFAULT_LIMIT;
		if (method.isAnnotationPresent(LogRTtimeLimit.class)) {
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {

				if (annotation.annotationType() == LogRTtimeLimit.class) {
					LogRTtimeLimit logRTtimeLimit = (LogRTtimeLimit) annotation;
					limitTime = logRTtimeLimit.limit();
				}
			}
		}
		endTimeMillis = System.currentTimeMillis(); // 记录方法执行完成的时间
		long diffLong = endTimeMillis - startTimeMillis;
		if (diffLong > limitTime) {
			log.error("RT OVER " + limitTime + "ms AND TIMES IS " + diffLong);
		}
		return pjp;
	}

}
